package com.hongpu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongpu.config.SecurityContextUtil;
import com.hongpu.domain.CoolTowerProject;
import com.hongpu.domain.CoolTowerProjectDetail;
import com.hongpu.dto.CoolTowerDto;
import com.hongpu.dto.CoolTowerProjectDto;
import com.hongpu.enums.CoolTowerProjectTypeEnum;
import com.hongpu.enums.CoolTowerWaterUnitEnum;
import com.hongpu.mapper.CoolTowerProjectMapper;
import com.hongpu.service.CoolTowerInfoService;
import com.hongpu.service.CoolTowerProjectAttendanceService;
import com.hongpu.service.CoolTowerProjectDetailService;
import com.hongpu.service.CoolTowerProjectService;
import com.hongpu.utils.ResultDto;
import com.hongpu.vo.CostStatisticsVo;
import com.hongpu.vo.SelectOptionVo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Michael zhang
 * @description 针对表【cool_tower_project(冷却塔安装项目管理)】的数据库操作Service实现
 * @createDate 2025-06-10 15:50:41
 */
@Service
public class CoolTowerProjectServiceImpl extends ServiceImpl<CoolTowerProjectMapper, CoolTowerProject>
        implements CoolTowerProjectService {

    @Autowired
    CoolTowerProjectMapper baseMapper;
    @Autowired
    CoolTowerInfoService coolTowerInfoService;
    @Autowired
    CoolTowerProjectDetailService coolTowerProjectDetailService;
    @Autowired
    CoolTowerProjectAttendanceService coolTowerProjectAttendanceService;

    /**
     * 冷却塔项目类型下拉列表
     */
    @Override
    public ResultDto optionList() {
        try {
            List<SelectOptionVo<String>> optionList = new ArrayList<>();
            CoolTowerProjectTypeEnum[] coolTowerProjectTypeEnums = CoolTowerProjectTypeEnum.values();
            for (CoolTowerProjectTypeEnum coolTowerProjectTypeEnum : coolTowerProjectTypeEnums) {
                SelectOptionVo<String> selectOptionVo = new SelectOptionVo<>();
                selectOptionVo.setLabel(coolTowerProjectTypeEnum.getDesc());
                selectOptionVo.setValue(coolTowerProjectTypeEnum.getType());
                optionList.add(selectOptionVo);
            }
            return ResultDto.ok(optionList);
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 新增
     *
     * @param coolTowerProject
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDto add(CoolTowerProject coolTowerProject) {
        try {
            coolTowerProject.setUnit(CoolTowerWaterUnitEnum.TON.getDesc());
            boolean save = save(coolTowerProject);
            // 保存冷却塔型号到冷却塔信息表（cool_tower_info）
            List<CoolTowerDto> coolTowerDtoList = coolTowerProject.getCoolTowerDtoList();
            if (coolTowerDtoList != null && coolTowerDtoList.size() > 0) {
                coolTowerDtoList.forEach(coolTowerDto -> {
                    coolTowerInfoService.addByModel(coolTowerDto.getModel());
                });
            }
            // 将 冷却塔信息保存到 cool_tower_project_detail
            if (coolTowerDtoList != null && coolTowerDtoList.size() > 0) {
                coolTowerDtoList.forEach(coolTowerDto -> {
                    Long coolTowerProjectId = coolTowerProject.getId();
                    CoolTowerProjectDetail coolTowerProjectDetail = new CoolTowerProjectDetail();
                    coolTowerProjectDetail.setCoolTowerProjectId(coolTowerProjectId).setCoolTowerInfoModel(coolTowerDto.getModel());
                    coolTowerProjectDetail.setNum(coolTowerDto.getNumber());
                    coolTowerProjectDetailService.toSave(coolTowerProjectDetail);
                });
            }
            return save ? ResultDto.ok() : ResultDto.fail();
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 修改
     *
     * @param coolTowerProject
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDto update(CoolTowerProject coolTowerProject) {
        try {
            boolean update = updateById(coolTowerProject);
            // 保存冷却塔型号到冷却塔信息表（cool_tower_info）
            List<CoolTowerDto> coolTowerDtoList = coolTowerProject.getCoolTowerDtoList();
            if (coolTowerDtoList != null && coolTowerDtoList.size() > 0) {
                coolTowerDtoList.forEach(coolTowerDto -> {
                    coolTowerInfoService.addByModel(coolTowerDto.getModel());
                });
            }
            // 将 冷却塔信息保存到 cool_tower_project_detail
            if (coolTowerDtoList != null && coolTowerDtoList.size() > 0) {
                // 根据 coolTowerProjectId 删除 cool_tower_project_detail中数据
                coolTowerProjectDetailService.deleteByCoolTowerProjectId(coolTowerProject.getId());
                // 重新保存冷却塔型号数据
                coolTowerDtoList.forEach(coolTowerDto -> {
                    Long coolTowerProjectId = coolTowerProject.getId();
                    CoolTowerProjectDetail coolTowerProjectDetail = new CoolTowerProjectDetail();
                    coolTowerProjectDetail.setCoolTowerProjectId(coolTowerProjectId).setCoolTowerInfoModel(coolTowerDto.getModel()).setNum(coolTowerDto.getNumber());
                    coolTowerProjectDetailService.toSave(coolTowerProjectDetail);
                });
            }
            return update ? ResultDto.ok() : ResultDto.fail();
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDto delete(Long id) {
        try {
            boolean delete = removeById(id);
            // 根据 coolTowerProjectId 删除 cool_tower_project_detail中数据
            coolTowerProjectDetailService.updateDeleted(id);
            return delete ? ResultDto.ok() : ResultDto.fail();
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 启用
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultDto active(Long id) {
        try {
            boolean active = baseMapper.active(id, SecurityContextUtil.getUserId());
            // 根据 coolTowerProjectId 激活 cool_tower_project_detail中数据
            coolTowerProjectDetailService.updateActive(id);
            return active ? ResultDto.ok() : ResultDto.fail();
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 分页
     *
     * @param coolTowerProjectDto
     */
    @Override
    public ResultDto page(CoolTowerProjectDto coolTowerProjectDto) {
        try {
            IPage<CoolTowerProject> page = new Page<>(coolTowerProjectDto.getCurrent(), coolTowerProjectDto.getSize());
            IPage<CoolTowerProject> selectPage = baseMapper.page(page, coolTowerProjectDto);
            // 给分页中的每个项目信息添加冷却塔型号信息
            List<CoolTowerProject> records = selectPage.getRecords();
            if (CollectionUtils.isNotEmpty(records)) {
                for (CoolTowerProject coolTowerProject : records) {
                    // 将项目信息补充完整
                    towerProjectInfo(coolTowerProject);
                }
            }
            return ResultDto.ok(selectPage);
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 根据项目ID查询项目名称
     *
     * @param id
     */
    @Override
    public String selectProjectNameById(Long id) {
        try {
            String projectName = null;
            QueryWrapper<CoolTowerProject> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id);
            CoolTowerProject coolTowerProject = baseMapper.selectOne(queryWrapper);
            if (coolTowerProject != null) {
                projectName = coolTowerProject.getName();
            }
            return projectName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据项目ID获取信息
     *
     * @param id
     */
    @Override
    public ResultDto coolTowerProjectInfo(Long id) {
        try {
            CoolTowerProject coolTowerProject = getById(id);
            // 将项目信息补充完整
            towerProjectInfo(coolTowerProject);
            return ResultDto.ok(coolTowerProject);
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    private synchronized CoolTowerProject towerProjectInfo(CoolTowerProject coolTowerProject) {
        Long coolTowerProjectId = coolTowerProject.getId();
        // 冷却塔型号及数量信息
        String coolTowerInfo = coolTowerProjectDetailService.selectCoolTowerInfoByCoolTowerProjectId(coolTowerProjectId);
        coolTowerProject.setCoolTowerInfo(coolTowerInfo);
        // 查询这个项目的总费用
        BigDecimal totalCost = coolTowerProjectAttendanceService.selectTotalCostByCoolTowerProjectId(coolTowerProjectId);
        coolTowerProject.setTotalCost(totalCost);
        // 查询这个项目的总工时
        BigDecimal workingHours = coolTowerProjectAttendanceService.selectNumberOfJobsByCoolTowerProjectId(coolTowerProjectId);
        coolTowerProject.setWorkingHours(workingHours);
        // 查询冷却塔的详细信息
        List<CoolTowerDto> coolTowerDtoList = coolTowerProjectDetailService.selectByCoolTowerProjectId(coolTowerProjectId);
        coolTowerProject.setCoolTowerDtoList(coolTowerDtoList);
        return coolTowerProject;
    }

    /**
     * 根据项目ID统计该项目的费用---点击填报时用的接口
     */
    @Override
    public ResultDto costStatistics(CoolTowerProjectDto coolTowerProjectDto) {
        try {
            Map<String, Object> resutl = new HashMap<>();
            // 工日总计
            BigDecimal allPersonWorkingHoursSum = BigDecimal.ZERO;
            // 费用总计
            BigDecimal allPersonTotalFeeSum = BigDecimal.ZERO;
            IPage<CostStatisticsVo> page = coolTowerProjectAttendanceService.costStatistics(coolTowerProjectDto);
            // 如果 page不为null，则统计 工日总计 和 费用总计
            if (page != null) {
                List<CostStatisticsVo> records = page.getRecords();
                if (CollectionUtils.isNotEmpty(records)) {
                    for (CostStatisticsVo costStatisticsVo : records) {
                        allPersonWorkingHoursSum = allPersonWorkingHoursSum.add(costStatisticsVo.getWorkingHoursSum());
                        allPersonTotalFeeSum = allPersonTotalFeeSum.add(costStatisticsVo.getTotalFeeSum());
                    }
                }
            }
            resutl.put("page", page);
            resutl.put("allPersonWorkingHoursSum", allPersonWorkingHoursSum);
            resutl.put("allPersonTotalFeeSum", allPersonTotalFeeSum);
            return ResultDto.ok(resutl);
        } catch (Exception e) {
            return ResultDto.fail(e.getLocalizedMessage());
        }
    }

    /**
     * 安装项目管理查询区域-安装项目下拉列表
     */
    @Override
    public ResultDto coolTowerProjectOptionList() {
        List<CoolTowerProject> list = list();
        List<SelectOptionVo<String>> selectOptionVoList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(list)){
        list.forEach(coolTowerProject -> {
            SelectOptionVo<String> selectOptionVo = new SelectOptionVo<>();
            selectOptionVo.setLabel(coolTowerProject.getId().toString());
            selectOptionVo.setValue(coolTowerProject.getName());
            selectOptionVoList.add(selectOptionVo);
        });
        }
        return ResultDto.ok(selectOptionVoList);
    }
}




